//
//  IntentionMainViewController.m
//  StraightTrain
//
//  Created by mk on 15/11/27.
//  Copyright © 2015年 mk. All rights reserved.
//

#import "IntentionMainViewController.h"
#import "PatientDetailsViewController.h"
#import "PaymentMainViewController.h"
#import "BookingDetailsViewController.h"

@interface IntentionMainViewController ()<PaymentMainViewControllerDelegate>
{
    NSString * strBookingTravelID;
    
    BOOL selectBeginDate;
    NSString * str_end_time;
    NSString * str_stark_time;
    
    int keyHeight;
}
@end

@implementation IntentionMainViewController

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self showPickerData:NO];
    [tevExplain resignFirstResponder];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
}



#pragma mark 创建pick
-(void)createPicker
{
    if (!viewDatepicker)
    {
        viewDatepicker = [[PickView alloc] init];
        viewDatepicker.delegate = self;
        viewDatepicker.backgroundColor = [UIColor whiteColor];
        viewDatepicker.tag = 100;
        [viewDatepicker setTranslatesAutoresizingMaskIntoConstraints:NO];
        //  viewDatepicker.pickMaxData = [dm dateFromString:@"2100-12-30"];
        [viewDatepicker setDataPick];
        [self.view addSubview:viewDatepicker];
        NSDictionary *views = NSDictionaryOfVariableBindings(viewDatepicker);
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0@1000-[viewDatepicker]-0@1000-|"
                                                                          options:0
                                                                          metrics:nil
                                                                            views:views]];
        
        NSLayoutConstraint *constraintHE = [NSLayoutConstraint constraintWithItem:self.view
                                                                        attribute:NSLayoutAttributeBottom
                                                                        relatedBy:NSLayoutRelationEqual
                                                                           toItem:viewDatepicker
                                                                        attribute:NSLayoutAttributeBottom
                                                                       multiplier:1
                                                                         constant:-206];
        [self.view addConstraint:constraintHE];
        
        NSLayoutConstraint *constraintV = [NSLayoutConstraint constraintWithItem:viewDatepicker
                                                                       attribute:NSLayoutAttributeHeight
                                                                       relatedBy:NSLayoutRelationEqual
                                                                          toItem:nil
                                                                       attribute:NSLayoutAttributeHeight
                                                                      multiplier:1
                                                                        constant:206];
        [self.view addConstraint:constraintV];
    }
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    titleLabel.text = @"就诊意向";
    
    [self createPicker];
    
    if ([gProjConfig.dicBookingTravelType allKeys].count>0)
    {
        NSArray * arrGenderK = [gProjConfig.dicBookingTravelType allKeys];
        NSArray * arrGenderV = [gProjConfig.dicBookingTravelType allValues];
        [btnVisitsType1 setTitle:[arrGenderV objectAtIndex:0] forState:UIControlStateNormal];
        btnVisitsType1.tag = [[arrGenderK objectAtIndex:0] integerValue];
        [btnVisitsType2 setTitle:[arrGenderV objectAtIndex:1] forState:UIControlStateNormal];
        btnVisitsType2.tag = [[arrGenderK objectAtIndex:1] integerValue];
        strBookingTravelID = [NSString stringWithFormat:@"%ld",(long)btnVisitsType1.tag];
    }
    
    //默认日期
    NSString * strbegDate = [viewDatepicker getOrAfterAFewDaysAgoWithDate:@"" days:1 back:YES];
    [btnBeginTime setTitle:strbegDate forState:UIControlStateNormal];
    [btnBeginTime setBackgroundImage:[[UIImage imageNamed:@"main_crerate_user_btn.png"] stretchableImageWithLeftCapWidth:20 topCapHeight:20] forState:UIControlStateNormal];
    
    NSString * strendDate = [viewDatepicker getOrAfterAFewDaysAgoWithDate:@"" days:8 back:YES];
    [btnEndTime setTitle:strendDate forState:UIControlStateNormal];
    [btnEndTime setBackgroundImage:[[UIImage imageNamed:@"main_crerate_user_btn.png"] stretchableImageWithLeftCapWidth:20 topCapHeight:20] forState:UIControlStateNormal];
    
    viewDatepicker.pickTitle.text = strbegDate;
    str_end_time = strendDate;
    str_stark_time = strbegDate;

     [imageTxvBG setImage:[[UIImage imageNamed:@"main_crerate_user_btn.png"] stretchableImageWithLeftCapWidth:20 topCapHeight:20]];
    
    imageTypeBG.layer.cornerRadius = 8;
    [scrollMain setAlwaysBounceVertical:YES];
    
}


-(IBAction)btnSelectVisitsType:(id)sender
{
    [self showPickerData:NO];
    [tevExplain resignFirstResponder];
    
    UIButton * btn = (UIButton *)sender;
    if (btn == btnVisitsType1)
    {
        [btnVisitsType1 setImage:[UIImage imageNamed:@"select_qyxy_down.png"] forState:UIControlStateNormal];
        [btnVisitsType2 setImage:[UIImage imageNamed:@"select_qyxy_up.png"] forState:UIControlStateNormal];
    }else
    {
        [btnVisitsType2 setImage:[UIImage imageNamed:@"select_qyxy_down.png"] forState:UIControlStateNormal];
        [btnVisitsType1 setImage:[UIImage imageNamed:@"select_qyxy_up.png"] forState:UIControlStateNormal];
    }
   // DLog(@"==%ld",(long)btn.tag);
   strBookingTravelID = [NSString stringWithFormat:@"%ld",(long)btn.tag];
}


-(IBAction)btnClickTime:(id)sender
{
    UIButton * btn = (UIButton *)sender;
    selectBeginDate = (btn == btnBeginTime)?YES:NO;
    
    if (!selectBeginDate)//结束时间设置最大值,最小值为开始时间7天之后
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        
        NSString * strbeg = [viewDatepicker getOrAfterAFewDaysAgoWithDate:str_stark_time days:7 back:YES];
        NSDate * minDate = [dateFormatter dateFromString:strbeg];
        
        NSString * strend = [viewDatepicker getOrAfterAFewDaysAgoWithDate:str_stark_time days:365 back:YES];
        NSDate * maxDate = [dateFormatter dateFromString:strend];
        [viewDatepicker setPickViewMaxData:maxDate];
        [viewDatepicker setPickViewMinData:minDate];
        [viewDatepicker setDefoultData:minDate];//默认
    }else
    {
        //最小值当前天数+1 最大无线 默认上次选中
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        
        NSString * strmin = [viewDatepicker getOrAfterAFewDaysAgoWithDate:@"" days:1 back:YES];
        NSDate * minDate = [dateFormatter dateFromString:strmin];
        [viewDatepicker setPickViewMinData:minDate];
        [viewDatepicker setPickViewMaxData:[dateFormatter dateFromString:@"2100-1-1"]];
        
        NSDate * defDate = [dateFormatter dateFromString:str_stark_time];
        [viewDatepicker setDefoultData:defDate];//默认
    }
    
    [self showPickerData:YES];
    [tevExplain resignFirstResponder];

}



#pragma mark 提交
-(IBAction)btnUpdateData:(id)sender
{
    [self showPickerData:NO];
    [tevExplain resignFirstResponder];
    
    NSString * strDateil = TextNsString(tevExplain.text);
    if (strDateil.length==0)
    {
        Alert(alerTitle, @"请填写详情描述,如无任何描述,请填写'无'", @"确定")
        return;
    }
     SetHUDStartText(@"提交信息..")
    NSMutableDictionary * dicData = [[NSMutableDictionary alloc]initWithCapacity:0];
    [dicData setObject:[gProjConfig.dicUserData objectForKey:USER_tel] forKey:@"patientbooking[username]"];
    [dicData setObject:[gProjConfig.dicUserData objectForKey:USER_token] forKey:@"patientbooking[token]"];
    [dicData setObject:self.strID forKey:@"patientbooking[patient_id]"];
    [dicData setObject:strBookingTravelID forKey:@"patientbooking[travel_type]"];
    [dicData setObject:str_stark_time forKey:@"patientbooking[date_start]"];
    [dicData setObject:str_end_time forKey:@"patientbooking[date_end]"];
    [dicData setObject:strDateil forKey:@"patientbooking[detail]"];
    
    NSString * strUrl = NullObjToString([gProjConfig.dicAllUrl objectForKey:@"createPatientbooking"]);
    [[HttpClient manager]POST:strUrl
                                 parameters:dicData
    success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         SetHUDHidden;
         if ([[responseObject objectForKey:requestDataKey] isKindOfClass:[NSDictionary class]])
         {
             NSString * strref = [[responseObject objectForKey:requestDataKey] objectForKey:@"refNo"];
             
             PaymentMainViewController * webview = [[PaymentMainViewController alloc]initWithNibName:@"PaymentMainViewController" bundle:nil];
             webview.delegate = self;
             MyNavigationController *navi  = [[MyNavigationController alloc]initWithRootViewController:webview];
             
             
             NSString * strUrl = [gProjConfig.dicAllUrl objectForKey:@"paymentUrl"];
            
             strUrl= [strUrl stringByReplacingOccurrencesOfString:@"refNo=#" withString:[NSString stringWithFormat:@"refNo=%@",strref]];
             strUrl= [strUrl stringByReplacingOccurrencesOfString:@"os=#" withString:@"os=ios"];
            // DLog(@"==%@",strUrl);
             webview.strUrl = strUrl;
             [self presentViewController:navi animated:YES completion:nil];
  
         }
        
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
        SetHUDHidden;
        HUDShowRequestError(error.domain, self.view)
     }];

}


#pragma mark 支付完成后跳转预约详情
-(void)hidderPayMentMainPaty
{
    BookingDetailsViewController * details = [[BookingDetailsViewController alloc]initWithNibName:@"BookingDetailsViewController" bundle:nil];
    details.strPatientId = self.strID;
    details.isMySender = YES;
    [self.navigationController pushViewController:details animated:NO];
    
    NSMutableArray * array =[[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
    [array removeObjectAtIndex:array.count-2];
    self.navigationController.viewControllers = array;
    
}


#pragma mark 保存
-(IBAction)btnSaveMess:(id)sender
{
    [self showPickerData:NO];
    [tevExplain resignFirstResponder];
    
    NSMutableArray * array =[[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
    
    UIViewController * cotroll = [self.navigationController.viewControllers objectAtIndex:array.count-2];

    if ([cotroll isKindOfClass:[PatientDetailsViewController class]])
    {
        [self.navigationController popViewControllerAnimated:YES];
    }else
    {
        PatientDetailsViewController * Details = [[PatientDetailsViewController alloc]initWithNibName:@"PatientDetailsViewController" bundle:nil];
        Details.strID = self.strID;
        Details.strTitle = @"患者详情";
        [self.navigationController pushViewController:Details animated:YES];
        
        array =[[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
        [array removeObjectAtIndex:array.count-2];
        self.navigationController.viewControllers = array;
    }
}

#pragma mark pickDelegate
-(void)toolBarDoneClick:(id)sender
{
    if (selectBeginDate)
    {
        [btnBeginTime setTitle:viewDatepicker.pickTitle.text forState:UIControlStateNormal];
        str_stark_time = viewDatepicker.pickTitle.text;
        
        NSString * strtime = [viewDatepicker getOrAfterAFewDaysAgoWithDate:str_stark_time days:7 back:YES];
        [btnEndTime setTitle:strtime forState:UIControlStateNormal];
        str_end_time = strtime;
        
    }
    else
    {
        [btnEndTime setTitle:viewDatepicker.pickTitle.text forState:UIControlStateNormal];
        str_end_time = viewDatepicker.pickTitle.text;
    }
}

#pragma mark showDataView
-(void)showPickerData:(BOOL)show
{
    for (NSLayoutConstraint *constraints in [self.view constraints]) {
        if (constraints.firstItem == self.view && constraints.secondItem == viewDatepicker && constraints.firstAttribute == NSLayoutAttributeBottom)
        {
            [UIView animateWithDuration:0.2 animations:^{
                constraints.constant = (show?0:-206);
                [self.view layoutIfNeeded];
            } completion:^(BOOL finished)
             {
             }];
            break;
        }
    }
    
}

-(void)textViewDidBeginEditing:(UITextView *)textView
{
    [self showPickerData:NO];
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
    {
        [textView resignFirstResponder];
        [scrollMain setContentOffset:CGPointMake(0,0) animated:YES];
        return NO;
    }
    return YES;
}

#pragma mark //当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyHeight = keyboardRect.size.height;
    
    [self changeViewFrame];
}

-(void)changeViewFrame
{
    int bottomDistance;
    bottomDistance = appScreenHeight - (64 + tevExplain.bottom);//键盘预留高度
    int content = (keyHeight + 30) - bottomDistance;
    if (content>0)
    {
        [scrollMain setContentOffset:CGPointMake(0,content) animated:YES];
    }
    
}

//
//-(void)textfieldContentWithoutAnimate:(NSLayoutConstraint *)constraint
//{
//    [UIView animateWithDuration:0.2 animations:^{
//        
//        [scrollMain setContentOffset:CGPointMake(0,0) animated:NO];
//        
//    }];
//}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [tevExplain resignFirstResponder];
}





-(IBAction)btnCleanAll:(id)sender
{
    [self showPickerData:NO];
    [tevExplain resignFirstResponder];
    [scrollMain setContentOffset:CGPointMake(0,0) animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
